﻿#region Usings
using System.Collections.Generic;
using System.Linq;
using System.Web;

using Castle.Core;
using Castle.MicroKernel;
using Castle.MicroKernel.Context;
using Castle.MicroKernel.Lifestyle;
#endregion

namespace BK.CastleUtils
{
    public class PerWebRequestLifestyleManager : Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleManager
    {
        #region Readonly & Static Fields
        private readonly TransientLifestyleManager _fallback;
        #endregion

        #region C'tors
        public PerWebRequestLifestyleManager()
        {
            _fallback = new TransientLifestyleManager();
        }
        #endregion

        #region Instance Methods
        public override void Dispose()
        {
            _fallback.Dispose();
            base.Dispose();
        }

        public override void Init(IComponentActivator componentActivator, IKernel kernel, ComponentModel model)
        {
            base.Init(componentActivator, kernel, model);
            _fallback.Init(componentActivator, kernel, model);
        }

        public override object Resolve(CreationContext context)
        {
            HttpContext current = HttpContext.Current;
            if (null == current || current.ApplicationInstance == null)
            {
                // fall back to transient behaviour if not in web context
                return _fallback.Resolve(context);
            }
            else
            {
                return base.Resolve(context);
            }
        }
        #endregion
    }
}